package com.laotou99.wmsjjj.wmsjjj.service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class Test1Service {

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private Redisson redisson;
	
	
	public void test1() { 
		System.out.println("Test1Service test1()");
		
		String lockKey = "lockKey";
		String clientId = UUID.randomUUID().toString();
		
//		redisTemplate.opsForValue().setIfAbsent(key, value)		
//		stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId,10,TimeUnit.SECONDS);
		
		try {
			Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId);
			Boolean result1 = stringRedisTemplate.expire(lockKey, 10L, TimeUnit.SECONDS);
			if(!result) {
				return;
			}
			
			int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
			if(stock>0) {
				int realStock = stock - 1;
				stringRedisTemplate.opsForValue().set("stock", realStock+"");
				System.out.println("stock is"+realStock);
			}else {
				System.out.println("no stock");
			} 
		} finally { 
			if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
				stringRedisTemplate.delete(lockKey);
			}
		}
	}

	
	public void test2() {
		System.out.println("test2()");
		
		String lockKey = "product_101";
		RLock redissonLock = redisson.getLock(lockKey);
		
		try {
			redissonLock.lock();
			int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
			if(stock>0) {
				int realStock = stock - 1;
				stringRedisTemplate.opsForValue().set("stock", realStock+"");
				System.out.println("stock is"+realStock);
			}else {
				System.out.println("no stock");
			} 
		} finally {

			redissonLock.unlock();
		}
		
		
		
		
		
	}
	
	
}
